package com.why.biyesheji.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.why.biyesheji.common.Constants;
import com.why.biyesheji.common.ServiceResultEnum;
import com.why.biyesheji.dao.CategoryMapper;
import com.why.biyesheji.dao.ProductMapper;
import com.why.biyesheji.pojo.Category;
import com.why.biyesheji.pojo.Product;
import com.why.biyesheji.service.ICategoryService;
import com.why.biyesheji.service.IProductService;
import com.why.biyesheji.util.PropertiesUtil;
import com.why.biyesheji.util.Result;
import com.why.biyesheji.util.ResultGenerator;
import com.why.biyesheji.vo.IndexNewProductVO;
import com.why.biyesheji.vo.ProductDetailVO;
import com.why.biyesheji.vo.ProductListVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by 华耀 王 on 2020/11/12
 **/
@Service("iProductService")
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ICategoryService iCategoryService;

    public int productAdd(Product product){
        int productRuselt = productMapper.insertSelective(product);
        return productRuselt;
    }

    public int productUpdate(Product product){
        int productRuselt = productMapper.updateByPrimaryKeySelective(product);
        return productRuselt;
    }

    public List<IndexNewProductVO> newProduct(){
        List<Product> newProduct = productMapper.newProduct();

        List<IndexNewProductVO> indexNewProductVOList = Lists.newArrayList();

        for (Product product : newProduct) {
            IndexNewProductVO indexNewProductVO = assembleNewProduct(product);
            indexNewProductVOList.add(indexNewProductVO);
        }
        return indexNewProductVOList;
    }

    @Override
    public Result productList(String keyword, Integer categoryId, int pageNum, int pageSize, String orderBy) {

        if (StringUtils.isBlank(keyword) && categoryId == null){
            return ResultGenerator.getFailResult("不合法的输入！");
        }

        List<Integer> categoryIdList = new ArrayList<Integer>();//保存查询到的商品分类和子分类new ArrayList<Integer>();
        if (categoryId != null){
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if (category == null && StringUtils.isBlank(keyword)){
                PageHelper.startPage(pageNum, pageSize);
                List<ProductListVO> productListVOList = Lists.newArrayList();
                PageInfo resultInfo = new PageInfo(productListVOList);
                return ResultGenerator.getSuccessResult(resultInfo);
            }

            categoryIdList = iCategoryService.selectCategoryAndChildById(category.getId());

        }
        if (StringUtils.isNotBlank(keyword)){
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
        }

        PageHelper.startPage(pageNum, pageSize);
        //排序处理,动态排序（Const声明常量，按价格排序）
        if (StringUtils.isNotBlank(orderBy)){
            if (Constants.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
                String[] orderByArray = orderBy.split("_");
                PageHelper.orderBy(orderByArray[0]+" "+orderByArray[1]);
            }
        }

        List<Product> productList = productMapper.selectByNameAndCategoryIds(StringUtils.isBlank(keyword) ? null : keyword,categoryIdList.size() == 0 ? null : categoryIdList);

        List<ProductListVO> productListVOList = Lists.newArrayList();
        for (Product product : productList) {
            ProductListVO productListVO = assembleProductListVO(product);
            productListVOList.add(productListVO);
        }

        PageInfo resultInfo = new PageInfo(productList);  // 要把刚从mybatis查询出来的数据放进pageInfo进行分页处理
        resultInfo.setList(productListVOList);
        return ResultGenerator.getSuccessResult(resultInfo);

    }

    @Override
    public Result productDetail(Integer id) {
        if (id == null){
            return ResultGenerator.getFailResult(Constants.ILLEGAL_ARGUMENT);
        }
        Product product = productMapper.selectByPrimaryKey(id);
        if (product == null){
            return ResultGenerator.getFailResult("产品已下架或者已删除！");
        }
        ProductDetailVO productDetailVO = assembleProductDetailVO(product);
        return ResultGenerator.getSuccessResult(productDetailVO);
    }

    private ProductDetailVO assembleProductDetailVO(Product product) {
        ProductDetailVO productDetailVO = new ProductDetailVO();
        productDetailVO.setId(product.getId());
        productDetailVO.setCategory(product.getCategory());
        productDetailVO.setName(product.getName());
        productDetailVO.setSubtitle(product.getSubtitle());
        productDetailVO.setDetail(product.getDetail());
        productDetailVO.setMainImage(product.getMainImage());
        List<String> productSubImages = Arrays.asList(product.getSubImages().split(","));
        productDetailVO.setSubImages(productSubImages);
        productDetailVO.setPrice(product.getPrice());
        productDetailVO.setStock(product.getStock());
        productDetailVO.setStatus(product.getStatus());
        //imageHost
        productDetailVO.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        productDetailVO.setCreateTime(product.getCreateTime());
        productDetailVO.setUpdateTime(product.getUpdateTime());
        return productDetailVO;
    }


    private ProductListVO assembleProductListVO(Product product) {
        ProductListVO productListVO = new ProductListVO();
        productListVO.setId(product.getId());
        productListVO.setCategoryId(product.getCategory());
        productListVO.setName(product.getName());
        productListVO.setSubtitle(product.getSubtitle());
        productListVO.setPrice(product.getPrice());
        productListVO.setStatus(product.getStatus());
        productListVO.setMainImage(product.getMainImage());
        productListVO.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        return productListVO;
    }


    private IndexNewProductVO assembleNewProduct(Product product){
        IndexNewProductVO indexNewProductVO = new IndexNewProductVO();
        indexNewProductVO.setId(product.getId());
        indexNewProductVO.setName(product.getName());
        indexNewProductVO.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        indexNewProductVO.setMainImage(product.getMainImage());
        indexNewProductVO.setSubtitle(product.getSubtitle());
        indexNewProductVO.setPrice(product.getPrice());
        return indexNewProductVO;
    }

}
